package net.sxnic.ugr.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sxnic.ugr.context.AppContext;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 
 * Introduction：安全登录过滤器
 * 210304开始不再使用，AccessIntercepter将使用此拦截器验证权限和session
 * @author 孙宇飞 create date : 2010-6-1
 */
@Component("loginFilter")
public class LoginFilter extends OncePerRequestFilter {

	private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

	private static String[] ignore;

	private static String loginUrl;
	
	private static String servletPath;


	/**
	 * @see org.springframework.web.filter.OncePerRequestFilter
	 *      #doFilterInternal(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		
		if (isIgnore(request)) {
			filterChain.doFilter(request, response);
			return;
		}


		String username = AppContext.getUserName(request);
		if (StringUtils.isNotBlank(username)) {
			logger.debug("------"+username+" reuqest url :"+request.getRequestURL()+" success~!");
			filterChain.doFilter(request, response);
			return;
		}

		logger.debug("not authentication asscess url :"
				+ request.getServletPath() + " , redrect to login.jsp");

		response.sendRedirect(request.getContextPath() + loginUrl);
		return;
	}

	

	/**
	 * TODO: DOCUMENT ME!
	 * 
	 * @param request
	 * @return
	 */
	private boolean isIgnore(HttpServletRequest request) {
//		String servletPath = request.getRequestURI();
//		
//		servletPath = StringUtils.remove(servletPath, "/zbkh");
				
		servletPath = request.getServletPath();
		
		if (StringUtils.isBlank(servletPath)) {
			return false;
		}

		if (servletPath.equals(loginUrl)) {
			return true;
		}

		for (String s : ignore) {
			if (servletPath.startsWith(s)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * TODO: DOCUMENT ME!
	 * 
	 * @param ignoreUrls
	 */
	public void setIgnore(String ignoreUrls) {
		String[] urls = ignoreUrls.split(",");

		int i = 0;
		for (String s : urls) {
			urls[i] = s.trim();
			i++;
		}

		ignore = urls;
	}

	/**
	 * TODO: DOCUMENT ME!
	 * 
	 * @param loginUrl
	 */
	public void setLoginURL(String loginUrl) {
		LoginFilter.loginUrl = loginUrl;
	}

}
